package cn.imu.controller;

import cn.imu.entity.User;
import cn.imu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(@RequestParam("username")String username,
                        @RequestParam("password")String password,
                        HttpSession session){

        User user = userService.selectUserByUsername(username);
        //从数据库中查user表中的用户进行展示


        if(user!=null){
        if (password.equals(user.getPassword())){//登录成功
            //将user对象存入session里
            session.setAttribute("user",user);
            //将status状态设置为login登录并且存入session
            session.setAttribute("status","login");
           /* int result=userLogService.insertUserLog(user.getUid());
            if (result > 0) {
                System.out.println("插入日志成功");
            } else {
                System.out.println("插入日志失败");
            }*/

            return "main";
        }else {//登录失败
            return "redirect:/register.html";
        }
        }
        return "main";
    }

    @RequestMapping ("/register")
    public String register(@RequestParam("username")String username,
                           @RequestParam("password")String password,
                           @RequestParam("age")int age,
                           HttpSession session){

        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAge(age);

       int result=userService.insertUser(user);
        System.out.println(result);
        if (result > 0) {
            System.out.println("用户注册成功");
            //从数据库中取出uid作为Userlog的外键
            user =userService.selectUserByUsername(username);
            session.setAttribute("user1",user);
            session.setAttribute("status","register");

            return "login";
        } else {
            System.out.println("用户注册失败");
            return "register";
        }

    }

    @RequestMapping ("/logout")
    @ResponseBody
    public String logout(HttpSession session){
        String status = (String) session.getAttribute("status");
        if (status.equals("login")){//退出成功
            session.invalidate();
            return "logout,success!";
        }else {//退出失败
            return "logout,failure!";
        }
    }
}
